//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
// 

#include "Application.h"
#include "app_pck_m.h"

Define_Module(Application);

void Application::initialize()
{
	event= new cMessage("event");
	waitTime= par("delayTime");

	scheduleAt(simTime()+waitTime,event);

	timeInterval.setRangeAutoUpper(0,100,1.5);
	delayHistogram.setRangeAuto(100,1.5);
	lastArrival=0;
	receivedPackets=0;
}

void Application::handleMessage(cMessage *msg){
	if (msg==event)
			handleSelfMessage();
		else
			handleMessageStats(msg);
}

void Application::handleSelfMessage(){
	waitTime= par("delayTime");
	scheduleAt(simTime()+waitTime,event);

	do{
		size= par("size");
	}while (size>1480 || size<26 || size%4!=0);
	App_pck *app_packet= new App_pck("application_packet");
	//set packet size
	app_packet->setSize(size);
	//set packet length
	app_packet->setByteLength(size);

	app_packet->setTimestamp();

	EV<<"App_pck was created.\n";
	send (app_packet, "toIP");
}

void Application::handleMessageStats(cMessage *msg)
{
	if(receivedPackets==0)
		lastArrival=simTime();
	else{
		EV<< "App_pck received"<< endl;
		timeInterval.collect(simTime()-lastArrival);
		delayHistogram.collect(simTime()-msg->getTimestamp());
		timeIntervalVector.record(simTime()-lastArrival);
		delayVector.record(simTime()-msg->getTimestamp());
		lastArrival=simTime();
	}
	receivedPackets++;
	drop(msg);
}


void Application::finish()
{
	EV<< "Host: "<< getParentModule()->getFullName()<<endl;
	EV<<"received: "<<receivedPackets<<" messages"<<endl;
	EV<<"min time interval: "<<timeInterval.getMin()<<endl;
	EV<<"max time interval: "<<timeInterval.getMax()<<endl;
	EV<<"mean time interval: "<<timeInterval.getMean()<<endl;
	EV<<"variance time interval: "<<timeInterval.getVariance()<<endl;
	EV<<"min delay time: "<<delayHistogram.getMin()<<endl;
	EV<<"max delay time: "<<delayHistogram.getMax()<<endl;
	EV<<"mean delay time: "<<delayHistogram.getMean()<<endl;
	EV<<"variance delay time: "<<delayHistogram.getVariance()<<endl;
	EV<<endl;
	timeInterval.recordAs("Packets arrival");
	delayHistogram.recordAs("Time delay");
}
